import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:puppy_store/models/category_model.dart';
import 'package:puppy_store/models/home_model.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_page.dart';
import 'package:puppy_store/pages/home/widgets/loadingAnimation.dart';
// import 'package:puppy_store/pages/home/widgets/loadingBg.dart';
import 'package:puppy_store/service/category_api.dart';
import 'package:puppy_store/widgets/custom_image.dart';
import 'package:puppy_store/widgets/price_widget.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({super.key});

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage>
    with AutomaticKeepAliveClientMixin {
  // 重写get wantKeepAlive, 返回true, 表示保持状态
  @override
  bool get wantKeepAlive => true;

  // 一级分类数据
  List<PrimaryCategoryModel> _primaryCategories = [];

  // 一级分类选中索引
  int _currentPrimaryCategoryIndex = 0;

  // 一级分类滚动视图控制器
  late ScrollController? _primaryCategoryListController;

  // 二级分类滚动视图控制器
  late ScrollController? _secondaryCategoryListController;

  // 获取list滚动组件的高度
  final GlobalKey _primaryCategoryClobalKey = GlobalKey(
    debugLabel: 'primaryCategoryClobalKey',
  );

  // 当前二级分类数据
  List<SubCategoryModel>? _subCategories;

  // 当前二级分类商品图片宽度
  double _imageWidth = 0.0;

  // 缓存二级分类的字典
  final Map<String, dynamic> _secondaryCatagoryCache = {};

  // 获取一级分类
  _loadPrimaryCategoryData() async {
    try {
      List<PrimaryCategoryModel> ctg = await CategoryApi.getPrimaryCategory();
      // 获得第一个分类的id
      String firstCategoryId = ctg[0].id!;
      // 获取二级分类
      _loadSecondaryCategoryData(firstCategoryId);

      setState(() {
        _primaryCategories = ctg;
      });
      // debugPrint("一级分类数据:${_primaryCategories.toString()}");
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  // 获取二级分类数据
  _loadSecondaryCategoryData(String id) async {
    SecondaryCategoryModel res;
    try {
      // 有缓存就从缓存中获取数据, 没有缓存就从网络中获取数据
      if (_secondaryCatagoryCache.containsKey(id)) {
        res = _secondaryCatagoryCache[id];
        setState(() {});
      } else {
        res = await CategoryApi.getSecondaryCategory(id);
        _secondaryCatagoryCache[id] = res;
      }

      setState(() {
        _subCategories = res.children!;
      });
    } catch (e) {
      debugPrint("发生错误了${e.toString()}");
    }
  }

  // 监听一级分类点击事件
  void _primaryCategoryOnTap(int index) {
    if (_currentPrimaryCategoryIndex == index) {
      return;
    }

    // 点击一级分类, 清空二级分类数据
    setState(() {
      _subCategories = null;
    });

    // 1. 获取选中一级分类的中心点
    double curCateCenter = index * 44 + 22;
    // 2. 获取一级分类滚动视图高度的一半
    RenderBox box =
        _primaryCategoryClobalKey.currentContext!.findRenderObject()
            as RenderBox;
    double priCateListHeight = box.size.height; // 一级分类可视区域高度
    double halfPriCateListHeight = priCateListHeight / 2;

    // 3. 计算滚动的中心位置
    double currentOffset = curCateCenter - halfPriCateListHeight;

    double minOffset = 0; // 最小可滚动距离
    double maxOffset =
        _primaryCategories.length * 44 - priCateListHeight; //最大可滚动距离

    // 这样也可以快读获得
    // double maxOffset2 =
    //     _primaryCategoryListController!.position.maxScrollExtent; //最大可滚动距离

    // 3.1 如果居中需要滚动的距离小于等于最小的滚动距离，则居中需要的滚动距离就是最小滚动距离值0
    if (currentOffset <= minOffset) {
      currentOffset = minOffset;
    }

    // 3.2 如果居中需要滚动的距离大于等于最大的滚动距离， 则居中需要的滚动距离就是最大滚动距离值
    if (currentOffset >= maxOffset) {
      currentOffset = maxOffset;
    }

    // 4. 滚动到中心位置
    _primaryCategoryListController!.animateTo(
      currentOffset,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );

    // 点击一级分类, 跳转到二级分类页面
    setState(() {
      _currentPrimaryCategoryIndex = index;
    });

    // 滚动二级分类组件
    if (_secondaryCategoryListController!.hasClients) {
      _secondaryCategoryListController!.jumpTo(0); // 不带动画滚动
    }

    // 加载二级分类数据
    String primaryCategoryId = _primaryCategories[index].id!;
    _loadSecondaryCategoryData(primaryCategoryId);
  }

  @override
  void initState() {
    _loadPrimaryCategoryData();
    // 初始化一级分类滚动视图控制器
    _primaryCategoryListController = ScrollController();

    // 初始化二级分类滚动视图控制器
    _secondaryCategoryListController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    // 释放一级分类滚动视图控制器
    _primaryCategoryListController!.dispose();

    // 释放二级分类滚动视图控制器
    _secondaryCategoryListController!.dispose();
    super.dispose();
  }

  Widget _buildPrimaryCategory() {
    return Container(
      color: Color(0xFFf2f2f2),
      child: ListView.builder(
        key: _primaryCategoryClobalKey,
        controller: _primaryCategoryListController,
        itemCount: _primaryCategories.length,
        itemBuilder: (context, index) {
          PrimaryCategoryModel primaryCategoryModel = _primaryCategories[index];
          return GestureDetector(
            onTap: () {
              _primaryCategoryOnTap(index);
            },
            child: Container(
              height: 44,
              decoration: BoxDecoration(
                color:
                    _currentPrimaryCategoryIndex == index
                        ? Colors.white
                        : Color(0xFFf7f7f8),
              ),
              alignment: Alignment.center,
              child: Row(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 2, right: 10),
                    child: Container(
                      width: 3,
                      height: 30,
                      decoration: BoxDecoration(
                        color:
                            _currentPrimaryCategoryIndex == index
                                ? Color(0xFF3CCEAF)
                                : Color(0xFFf7f7f8),
                        borderRadius: BorderRadius.circular(3),
                      ),
                    ),
                  ),

                  Expanded(
                    child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        '${primaryCategoryModel.name}',
                        style: TextStyle(
                          color: Color(0xff333333),
                          fontSize: 13,
                          fontWeight:
                              _currentPrimaryCategoryIndex == index
                                  ? FontWeight.bold
                                  : FontWeight.normal,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // 构建二级分类组件方法
  Widget _buildSecondaryCategory() {
    if (_subCategories != null) {
      return Container(
        color: Colors.white,
        child: ListView.builder(
          controller: _secondaryCategoryListController,
          itemBuilder: (BuildContext context, int index) {
            SubCategoryModel subCategoryModel = _subCategories![index];
            return _buildCategoryGoodsItem(subCategoryModel);
          },
          itemCount: _subCategories!.length,
        ),
      );
    }
    // 这里放默认图片占位
    // return LoadingImgWidget();
    return LoadingAnimation();
  }

  /// 构建二级分类下的商品
  Widget _buildCategoryGoodsItem(SubCategoryModel subCategoryModel) {
    return Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: Column(
        children: [
          Column(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 5, right: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      subCategoryModel.name!,
                      style: TextStyle(
                        fontSize: 13.0,
                        color: Color(0xFF333333),
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "全部 >>",
                        style: TextStyle(
                          fontSize: 11.0,
                          color: Color(0xFF999999),
                        ),
                      ),
                      onTap: () {},
                    ),
                  ],
                ),
              ),

              Padding(
                padding: EdgeInsets.only(top: 8.0),
                child: Container(
                  height: 1.0,
                  decoration: BoxDecoration(color: Color(0xFFF7F7F8)),
                ),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10, right: 10),
            child: StaggeredGridView.countBuilder(
              crossAxisCount: 3,
              itemCount: subCategoryModel.goods!.length,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 24.0,
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int index) {
                GoodsModel goodsModel = subCategoryModel.goods![index];

                return GestureDetector(
                  onTap: () {
                    // 跳转到商品详情页面
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (context) {
                          return GoodsDetailPage(
                            id: subCategoryModel.goods![index].id!,
                          );
                        },
                      ),
                    );
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CustomImage(
                        url: goodsModel.picture!,
                        width: _imageWidth,
                        height: _imageWidth,
                      ),
                      Text(
                        goodsModel.name!,
                        style: TextStyle(
                          fontSize: 11.0,
                          color: Color(0xFF333333),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.clip,
                      ),

                      Padding(
                        padding: EdgeInsets.only(top: 8.0),
                        child: PriceWidget(
                          price: goodsModel.price!,
                          symbolFontSize: 11.0,
                          integerFontSize: 11.0,
                          decimalFontSize: 11.0,
                        ),
                      ),
                    ],
                  ),
                );
              },
              staggeredTileBuilder: (int index) {
                return StaggeredTile.fit(1);
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 调用父类的build方法, 否则会报错:
    super.build(context);

    // 屏幕宽度
    double screenWidth = MediaQuery.of(context).size.width;
    // 图片宽度
    _imageWidth = ((screenWidth / 4 * 3) - (4 * 10.0)) / 3;

    return Scaffold(
      backgroundColor: Color(0xffF7F7F8),
      appBar: AppBar(
        title: Text(
          '分类',
          style: TextStyle(color: Color(0xFF282828), fontSize: 16),
        ),
        centerTitle: true,
        shadowColor: Colors.grey.withAlpha(80),
        elevation: 3,
        backgroundColor: Colors.white,
      ),
      body: Padding(
        padding: EdgeInsets.only(top: 6),
        child: Row(
          children: [
            // 一级分类
            Expanded(flex: 1, child: _buildPrimaryCategory()),

            // 二级分类
            Expanded(
              flex: 3,
              child: Container(
                height: double.infinity,
                color: Colors.white,
                child: _buildSecondaryCategory(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
